package com.screen.screendisplay.controller;

import com.screen.screendisplay.common.pojo.ApiResponse;
import com.screen.screendisplay.service.al.AlProdoperPrdSitService;
import com.screen.screendisplay.vo.al.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 能源消费表 前端控制器
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Tag(name = "铝业产业", description = "铝业产业")
@RestController
@RequestMapping("/al")
public class AlContrroller {

    @Autowired
    private AlProdoperPrdSitService alProdoperPrdSitService;

    @Autowired
    private com.screen.screendisplay.service.al.AlProdoperPrdQualService alProdoperPrdQualService;

    @Autowired
    private com.screen.screendisplay.service.al.AlProdoperStockService alProdoperStockService;

    @Autowired
    private com.screen.screendisplay.service.al.AlProdoperStationPerService alProdoperStationPerService;

    @Autowired
    private com.screen.screendisplay.service.al.AlProdoperSalesService alProdoperSalesService;

    @Autowired
    private com.screen.screendisplay.service.al.AlOverviewItemService alOverviewItemService;

    @Autowired
    private com.screen.screendisplay.service.al.AlOpermonEqpStateService alOpermonEqpStateService;

    @Autowired
    private com.screen.screendisplay.service.al.AlSafetyenvAlarmService alSafetyenvAlarmService;


    @Operation(summary = "生产经营-生产情况-铝液生产情况", description = "获取铝液生产情况数据，包含月度计划完成量、实际完成量、完成率等指标")
    @GetMapping(value = "/prodoper/production/al-liquid")
    public ApiResponse<List<AlProdoperPrdSitVO>> getAluminumLiquidProduction(@RequestParam(value = "year", required = false) Integer year) {
        // 使用当前年份或传入的年份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        
        // 查询铝液生产数据，product_type=0表示铝液
        List<AlProdoperPrdSitVO> productionData = alProdoperPrdSitService.getProductionDataByYearAndType(currentYear, (byte) 0);
        
        return ApiResponse.succeed(productionData);
    }

    @Operation(summary = "生产经营-生产情况-铝锭生产情况", description = "生产经营-生产情况-铝锭生产情况")
    @GetMapping(value = "/prodoper/production/al-ingot")
    public ApiResponse<List<AlProdoperPrdSitVO>> m2(@RequestParam(value = "year", required = false) Integer year) {
        // 使用当前年份或传入的年份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        
        // 查询铝锭生产数据，product_type=1表示铝锭
        List<AlProdoperPrdSitVO> productionData = alProdoperPrdSitService.getProductionDataByYearAndType(currentYear, (byte) 1);
        
        return ApiResponse.succeed(productionData);
    }

    @Operation(summary = "生产经营-生产情况-碳素阳极生产情况", description = "生产经营-生产情况-碳素阳极生产情况")
    @GetMapping(value = "/prodoper/production/carbon-anode")
    public ApiResponse<List<AlProdoperPrdSitVO>> m3(@RequestParam(value = "year", required = false) Integer year) {
        // 使用当前年份或传入的年份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        
        // 查询碳素阳极生产数据，product_type=2表示碳素阳极
        List<AlProdoperPrdSitVO> productionData = alProdoperPrdSitService.getProductionDataByYearAndType(currentYear, (byte) 2);
        
        return ApiResponse.succeed(productionData);
    }

    @Operation(summary = "生产经营-生产质量-铝产量质量", description = "获取铝液生产质量数据，包含当期品率和同期品率等指标")
    @GetMapping(value = "/prodoper/quality/al-yield")
    public ApiResponse<List<AlProdoperPrdQualOneVO>> getAluminumQuality(@RequestParam(value = "year", required = false) Integer year) {
        // 查询铝产量质量数据
        List<AlProdoperPrdQualOneVO> qualityData = alProdoperPrdQualService.getAluminumQualityData();
        return ApiResponse.succeed(qualityData);
    }

    @Operation(summary = "生产经营-生产质量-低铁铝率", description = "生产经营-生产质量-低铁铝率")
    @GetMapping(value = "/prodoper/quality/low-iron-rate")
    public ApiResponse<List<AlProdoperPrdQualTwoVO>> m5(@RequestParam(value = "year", required = false) Integer year) {
        // 查询低铁铝率数据
        List<AlProdoperPrdQualTwoVO> qualityData = alProdoperPrdQualService.getLowIronAluminumRateData();
        return ApiResponse.succeed(qualityData);
    }

    @Operation(summary = "生产经营-生产质量-碳素阳极质量", description = "生产经营-生产质量-碳素阳极质量")
    @GetMapping(value = "/prodoper/quality/anode-quality")
    public ApiResponse<List<AlProdoperPrdQualThreeVO>> m6(@RequestParam(value = "year", required = false) Integer year) {
        // 查询碳素阳极质量数据
        List<AlProdoperPrdQualThreeVO> qualityData = alProdoperPrdQualService.getCarbonAnodeQualityData();
        return ApiResponse.succeed(qualityData);
    }

    @Operation(summary = "生产经营-库存情况-铝合金产品存量", description = "获取铝合金产品库存数据，包含最近12个月的库存量变化趋势")
    @GetMapping(value = "/prodoper/inventory/alloy-stock")
    public ApiResponse<List<AlProdoperStockVO>> getAlloyStockData(@RequestParam(value = "year", required = false) Integer year) {
        // 查询铝合金产品库存数据
        List<AlProdoperStockVO> stockData = alProdoperStockService.getAlloyStockData();
        return ApiResponse.succeed(stockData);
    }

    @Operation(summary = "生产经营-库存情况-霍林河/白音华绿电火电占比", description = "获取霍林河和白音华电厂绿电火电占比数据，展示12个月的清洁能源使用情况")
    @GetMapping(value = "/prodoper/inventory/power-ratio")
    public ApiResponse<List<AlProdoperStationPerVO>> getPowerStationRatio(@RequestParam(value = "year", required = false) Integer year) {
        // 查询电厂绿电火电占比数据
        List<AlProdoperStationPerVO> powerRatioData = alProdoperStationPerService.getPowerStationRatio();
        return ApiResponse.succeed(powerRatioData);
    }


    @Operation(summary = "生产经营-销售情况-铝液销售情况", description = "获取铝液销售情况数据，包含12个月的计划销售量、实际销售量、完成率等关键指标")
    @GetMapping(value = "/prodoper/sales/al-liquid")
    public ApiResponse<List<AlProdoperSalesVO>> getLiquidSales(@RequestParam(value = "year", required = false) Integer year) {
        // 查询铝液销售数据
        List<AlProdoperSalesVO> salesData = alProdoperSalesService.getLiquidSalesData();
        return ApiResponse.succeed(salesData);
    }

    @Operation(summary = "生产经营-销售情况-铝锭销售情况", description = "生产经营-销售情况-铝锭销售情况")
    @GetMapping(value = "/prodoper/sales/al-ingot")
    public ApiResponse<List<AlProdoperSalesVO>> getAlIngotSales(@RequestParam(value = "year", required = false) Integer year) {
        // 查询铝锭销售数据
        List<AlProdoperSalesVO> salesData = alProdoperSalesService.getIngotSalesData();
        return ApiResponse.succeed(salesData);
    }

    @Operation(summary = "产业指标-综合技术指标看板", description = "获取铝业产业综合技术指标数据，包含铝产品年产量、电解铝年产能、炭素年产量等关键指标")
    @GetMapping(value = "/overview/tech-indicators")
    public ApiResponse<AlOverviewTechIndicatorsVO> getTechIndicatorsOverview(@RequestParam(value = "year", required = false) Integer year) {
        // 查询最新的综合技术指标数据
        AlOverviewTechIndicatorsVO techIndicators = alOverviewItemService.getLatestTechIndicators();
        return ApiResponse.succeed(techIndicators);
    }

    @Operation(summary = "运行监测-设备状态监测", description = "获取铝业产业各电厂设备状态数据，包含电解槽和整流机组的运行状态统计")
    @GetMapping(value = "/opermon/equipment-state")
    public ApiResponse<List<AlOpermonEquipmentStateVO>> getEquipmentStateMonitoring(@RequestParam(value = "year", required = false) Integer year) {
        // 查询所有铝厂的最新设备状态数据
        List<AlOpermonEquipmentStateVO> equipmentStateList = alOpermonEqpStateService.getLatestEquipmentState();
        return ApiResponse.succeed(equipmentStateList);
    }

    @Operation(summary = "运行监测-能源消费监测", description = "运行监测-能源消费监测")
    @GetMapping(value = "/opermon/energy-consumption")
    public ApiResponse<List<AlOpermonEnergyConsumptionVO>> m13(@RequestParam(value = "year", required = false) Integer year) {
        // 查询前10条环保指标数据
        List<com.screen.screendisplay.entity.al.AlSafetyenvAlarm> alarmList = alSafetyenvAlarmService.list(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.screen.screendisplay.entity.al.AlSafetyenvAlarm>()
                .orderByDesc("id")
                .last("LIMIT 10")
        );
        
        // 转换为VO对象
        List<AlOpermonEnergyConsumptionVO> result = new ArrayList<>();
        for (com.screen.screendisplay.entity.al.AlSafetyenvAlarm alarm : alarmList) {
            AlOpermonEnergyConsumptionVO vo = new AlOpermonEnergyConsumptionVO();
            vo.setPmRealValue(alarm.getPmRealValue());
            vo.setPmStandardValue(alarm.getPmStandardValue());
            vo.setSo2RealValue(alarm.getSo2RealValue());
            vo.setSo2StandardValue(alarm.getSo2StandardValue());
            vo.setFluorideRealValue(alarm.getFluorideRealValue());
            vo.setFluorideStandardValue(alarm.getFluorideStandardValue());
            vo.setUnitCode(alarm.getUnitCode());
            vo.setUnitName(alarm.getUnitName());
            result.add(vo);
        }
        
        return ApiResponse.succeed(result);
    }

    @Operation(summary = "安全环保-环保数据实时监测", description = "安全环保-环保数据实时监测")
    @GetMapping(value = "/safetyenv/env-indicators")
    public ApiResponse<AlSafetyenvEnvIndicatorsVO> m14(@RequestParam(value = "year", required = false) Integer year) {
        // 创建环保指标数据
        AlSafetyenvEnvIndicatorsVO vo = new AlSafetyenvEnvIndicatorsVO();
        vo.setSo2YearlyEmission(new BigDecimal("5267.85"));
        vo.setPmYearlyEmission(new BigDecimal("8934.56"));
        vo.setFluorideYearlyEmission(new BigDecimal("3421.78"));
        
        return ApiResponse.succeed(vo);
    }

    @Operation(summary = "铝厂简介", description = "铝厂简介")
    @GetMapping(value = "/aluminum/factory/intro")
    public ApiResponse<AluminumFactoryIntroVO> getAluminumFactoryIntro(@RequestParam(value = "unitCode", required = false) String unitCode) {
        // Mock数据
        AluminumFactoryIntroVO vo = new AluminumFactoryIntroVO();
        
        // 根据unitCode设置铝厂名称
        String factoryName = "霍煤鸿骏铝厂"; // 默认值
        if (unitCode != null) {
            switch (unitCode) {
                case "E_01_01":
                    factoryName = "霍煤鸿骏铝厂";
                    break;
                case "E_01_02":
                    factoryName = "白音华铝厂";
                    break;
                case "E_01_03":
                    factoryName = "扎哈淖尔铝厂";
                    break;
                default:
                    factoryName = "霍煤鸿骏铝厂";
                    break;
            }
        }
        
        vo.setFactoryName(factoryName);
        vo.setImageUrl("/images/aluminum/factory.jpg");
        vo.setIntroduction("霍煤鸿骏铝电公司成立于2002年11月，地处内蒙古自治区霍林郭勒市，公司依托当地煤炭资源丰富，打造了煤—电—铝循环经济产业链模式，具有年产能80万吨，炭素产能20万吨的生产规模。企业先后获得中国AAA级信用企业、自治区级绿色企业、以虚强体企业、国家级绿色矿山称号，是国家循环经济示范企业，以虚强体企业为主导方向，坚持创新驱动，发展绿色经济。");
        vo.setEstablishedDate("2002年11月");
        vo.setAnnualCapacity("铝产能80万吨/年，炭素产能20万吨/年");
        vo.setMainProducts("电解铝、炭素制品");
        return ApiResponse.succeed(vo);
    }

    @Operation(summary = "铝厂生产情况", description = "铝厂生产情况")
    @GetMapping(value = "/aluminum/production/status")
    public ApiResponse<AluminumProductionStatusVO> getAluminumProductionStatus(@RequestParam(value = "unitCode", required = false) String unitCode) {
        // Mock数据
        AluminumProductionStatusVO vo = new AluminumProductionStatusVO();
        vo.setAluminumLiquidDaily(new BigDecimal("4.57"));
        vo.setAluminumIngotDaily(new BigDecimal("5.61"));
        vo.setCarbonAnodeDaily(new BigDecimal("4.82"));
        return ApiResponse.succeed(vo);
    }

    @Operation(summary = "铝厂生产效率和能耗", description = "铝厂生产效率和能耗")
    @GetMapping(value = "/aluminum/production/efficiency")
    public ApiResponse<AluminumProductionEfficiencyVO> getAluminumProductionEfficiency(@RequestParam(value = "unitCode", required = false) String unitCode) {
        // Mock数据
        AluminumProductionEfficiencyVO vo = new AluminumProductionEfficiencyVO();
        vo.setCurrent300KA(new BigDecimal("308"));
        vo.setCurrent350KA(new BigDecimal("370"));
        vo.setVoltage300KA(new BigDecimal("4.04"));
        vo.setVoltage400KA(new BigDecimal("4.03"));
        
        // 构造最近7日用电负荷趋势数据
        List<AluminumProductionEfficiencyVO.PowerLoadItem> powerLoadTrend = new ArrayList<>();
        LocalDate today = LocalDate.now();
        for (int day = 6; day >= 0; day--) {
            AluminumProductionEfficiencyVO.PowerLoadItem item = new AluminumProductionEfficiencyVO.PowerLoadItem();
            LocalDate date = today.minusDays(day);
            item.setTime(date.toString()); // 格式: YYYY-MM-DD
            // 生成波动的用电负荷数据（基准60万千瓦，波动范围±20）
            double baseLoad = 60.0;
            double variation = Math.sin(day * Math.PI / 3.5) * 15 + (Math.random() - 0.5) * 10;
            item.setPowerLoad(new BigDecimal(String.format("%.2f", baseLoad + variation)));
            powerLoadTrend.add(item);
        }
        vo.setPowerLoadTrend(powerLoadTrend);
        
        return ApiResponse.succeed(vo);
    }

    @Operation(summary = "铝厂安全环保", description = "铝厂安全环保")
    @GetMapping(value = "/aluminum/safety-env")
    public ApiResponse<AluminumSafetyEnvVO> getAluminumSafetyEnv(@RequestParam(value = "unitCode", required = false) String unitCode) {
        // Mock数据
        AluminumSafetyEnvVO vo = new AluminumSafetyEnvVO();
        
        // 二氧化硫浓度监测
        AluminumSafetyEnvVO.PollutionMonitor so2Monitor = new AluminumSafetyEnvVO.PollutionMonitor();
        so2Monitor.setPollutantName("二氧化硫浓度");
        so2Monitor.setRealTimeValue(new BigDecimal("22"));
        so2Monitor.setHistoricalValue(new BigDecimal("24"));
        vo.setSo2Monitor(so2Monitor);
        
        // 氮化物浓度监测
        AluminumSafetyEnvVO.PollutionMonitor noxMonitor = new AluminumSafetyEnvVO.PollutionMonitor();
        noxMonitor.setPollutantName("氮化物浓度");
        noxMonitor.setRealTimeValue(new BigDecimal("18"));
        noxMonitor.setHistoricalValue(new BigDecimal("16"));
        vo.setNoxMonitor(noxMonitor);
        
        // 颗粒物浓度监测
        AluminumSafetyEnvVO.PollutionMonitor pmMonitor = new AluminumSafetyEnvVO.PollutionMonitor();
        pmMonitor.setPollutantName("颗粒物浓度");
        pmMonitor.setRealTimeValue(new BigDecimal("14"));
        pmMonitor.setHistoricalValue(new BigDecimal("14"));
        vo.setPmMonitor(pmMonitor);
        
        return ApiResponse.succeed(vo);
    }

}
